<template>
  <div style="width:100%;height:100%">
    <configTable
    ref="newCusTable"
    :headers="headers"
    :data="tableData"
    :pagingData="pagingData"
    @pageChange="handleCurrentChange"
    @pageSizeChange="handleSizeChange"
    @checkHeadersChange="checkHeadersChange"
    :headersConfig="headersConfig"
    :batchs="batchs"
    :selection="selection"
    :showPagination="showPagination"
    @batchClick="batchClick"
    :dynamic="true"
  >
    <template slot="column">
      <template v-if="checkHeaders && checkHeaders.length">
        <template v-for="(item, index) in checkHeaders" >
          <u-table-column :key="index" :label="afterSales ? fieldsMap[item] : item.label" v-if="item.show || afterSales" :fixed="['oprate'].includes(afterSales ? item : item.prop) ? 'right' : false">
            <template slot-scope="{ row }">
              <!-- 客户标签 -->
              <template v-if="['labels'].includes(afterSales ? item : item.prop)">
                  <div
                    v-for="(v, k) in row[`${afterSales ? item : item.prop}_bak`]"
                    :key="k"
                    class="cus-tags"
                    :style="{
                      color: v && v.color && v.color !== '#ffffff' ? '#fff' : '#999',
                      background: v && v.color ? v.color : '#fff',
                      border: v && v.color === '#ffffff' ? '1px solid #999' : 'none',
                    }">
                    {{ v && v.name }}
                  </div>
              </template>
              <!-- 售后云的省市县处理 -->
              <template v-else-if="['province', 'city', 'area'].includes(afterSales && item)">{{ areaMap[row[item]] }}</template>
              <!-- 售后云的字段直接回显，不需要特殊处理的 -->
              <template v-else-if="['contactName', 'detailAddress', 'phone', 'contactEmail'].includes(afterSales && item)">{{ row[item] }}</template>
              <!-- 操作栏 -->
              <template v-else-if="['oprate'].includes(afterSales ? item : item.prop)">
                <span v-if="afterSales" @click.stop="del(row.id)" class="oprate delete">删除</span>
                <span v-else class="oprate-span" v-functions="['customer_edit']"  @click="edit(row, 'edit')">详情</span>
              </template>
              <!-- 附件处理，要允许下载 -->
              <template v-else-if="['attachments'].includes(afterSales ? item : item.prop)">
                <p v-for="(attachmentItem, index) in row['attachments']" :key="index">
                  <a :href="attachmentItem.id" target="_blank" download>{{ attachmentItem.name }}</a>
                </p>
              </template>
              <!-- 字段直接回显，无需特殊处理的 -->
              <template v-else>{{ row[`${afterSales? item :item.prop}_bak`] }}</template>
            </template>
          </u-table-column>
        </template>
      </template>
      <template v-else>
        <u-table-column>
        </u-table-column>
      </template>
    </template>
  </configTable>
  </div>

</template>

<script lang="ts">
/**
 * 客户表格
 */
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { checkHideTel } from '@/utils/common'
import { CommonModule } from '@/store/modules/common/index'
@Component({
  name: 'NoticeSetting',
  components: {
    configTable
  }
})
export default class NoticeSetting extends Vue {
  [x: string]: any
  @Prop() private pagingData!: {}
  @Prop({ default: () => [] }) private headers!: any[]
  @Prop({ default: () => [] }) private checkHeaders!: any[]
  @Prop({ default: () => [] }) private batchs!: any[] // 批量操作
  @Prop({ default: () => true }) private showPagination!: boolean // 是否展示翻页，默认展示
  @Prop({ default: () => false }) private headersConfig!: boolean // 是否展示配置表头，默认不展示
  @Prop({ default: () => false }) private selection!: boolean // 全选框，默认不展示
  @Prop({ default: () => false }) private afterSales!: boolean // 是否是售后云
  @Prop({ default: () => [] }) private data!: any[] // table的数据
  @Prop({ default: () => [] }) private fieldsMap!: any[] // 售后云传递过来的
  private areaList: any = []
  private areaMap: any = {}
  private tableData: any = []

  @Watch('data')
  private async dataChange (cur) {
    if (!this.$store.state.common.publicCache.region?.result) { // 若渲染时，还没有省市县的缓存，先拉取一下
      await this.getRegionCache()
    }
    const labels = this.$store.state.common.publicCache.customerAllLabels || []
    const fields = this.$store.state.common.publicCache.customerAllFields || []
    if (labels && labels.length <= 0) { // 没有标签，取一下
      await this.getCustomerAllLabels()
    }
    if (fields && fields.length <= 0) { // 没有客户自定义字段，取一下
      await this.getCustomerFiled()
    }
    this.tableData = this.handleTableList(cur)
  }

  @Watch('getRegion', { immediate: true })
  private hanleAreaMap (cur) {
    const labels = {}
    const handleFn = (list) => {
      list.map(item => {
        labels[item.id] = item.fullname
        if (item.children) {
          handleFn(item.children)
        }
      })
    }
    if (cur && Array.isArray(cur)) {
      handleFn(cur)
    }
    this.areaMap = labels || {}
  }

  get getAllLabels () {
    return (CommonModule as any).publicCache.customerAllLabelsObj
  }

  get getCustomerAllFields () {
    const fields = this.$store.state.common.publicCache.customerAllFields || []
    const newObj: any = {}
    if (fields && Array.isArray(fields)) {
      fields.map(item => {
        newObj[item.field] = item
      })
    }
    return newObj
  }

  get getRegion () {
    return this.$store.state.common.publicCache?.region?.result || []
  }

  private cancelSelectFun () {
    this.$nextTick(() => {
      (this as any).$refs.newCusTable.cancelSelectFun()
    })
  }

  private getCusLables (id) {
    const labels = this.getAllLabels[id]
    if (labels && labels.name) {
      return labels
    }
    return {}
  }

  private del (id) {
    this.$emit('del', id)
  }

  private edit (data: any, type: string) {
    this.$emit('edit', data, type)
  }

  private getGender (type: any) {
    switch (type) {
      case 'F':
        return '女'
      case 'M':
        return '男'
      case 'N':
        return '保密'
    }
  }

  private handleArea (arr) { // 匹配省市县
    let str = ''
    const handleFn = (list) => {
      let listStr = ''
      list.map(item => {
        if (item && Array.isArray(item)) {
          handleFn(item)
        } else {
          listStr += `${this.areaMap[item] || ''}/`
        }
      })
      listStr = listStr.substring(0, listStr.length - 1)
      str += `${listStr} 、`
    }
    if (arr && Array.isArray(arr)) {
      handleFn(arr)
      str = str.substring(0, str.length - 1)
    }
    return str
  }

  private handleTableList (tablelist) {
    tablelist.map(item => {
      Object.keys(item).forEach(keyItem => {
        if (['mobile', 'qq', 'wechat', 'email'].includes(keyItem)) { // 多选处理
          if (item[keyItem] && Array.isArray(item[keyItem])) {
            if (keyItem === 'mobile') { // 手机号加密
              item[`${keyItem}_bak`] = (item[keyItem].map(v => checkHideTel(v.value))).join('、')
            } else {
              item[`${keyItem}_bak`] = (item[keyItem].map(v => v.value)).join('、')
            }
          } else { // 部分数据是字符串类型的, 联系人邮箱
            item[`${keyItem}_bak`] = item[keyItem]
          }
        } else if (keyItem === 'gender' && item[keyItem]) { // 性别
          item[`${keyItem}_bak`] = this.getGender(item[keyItem])
        } else if (keyItem === 'labels' && item[keyItem]) { // 客户标签
          item[`${keyItem}_bak`] = item[keyItem].map(id => {
            return this.getCusLables(id)
          })
        } else if (['lastCallUser', 'lastChatUser', 'updateUser', 'createUser', 'firstOwner', 'owner'].includes(keyItem)) { // 跟人有关的
          const agentObj = this.$store.state.common.publicCache.userListObj[item[keyItem]] // 座席
          item[`${keyItem}_bak`] = agentObj ? agentObj.name : '--'
        } else if (keyItem === 'region') { // 省市县
          item[`${keyItem}_bak`] = this.handleArea(item[keyItem])
        } else { // 其他自定义字段
          item[`${keyItem}_bak`] = this.handleCutomFile(keyItem, item[keyItem])
        }
      })
    })
    console.log(tablelist)
    return tablelist
  }

  private handleCutomFile (field, key) { // 处理table的自定义字段
    const obj = this.getCustomerAllFields[field]
    let str = ''
    if (obj) {
      if (['checkbox', 'radio', 'dropdown', 'cascade'].includes(obj.type)) { // 多选 || 单选 || 下拉 || 级联
        let arr = []
        if (['cascade'].includes(obj.type)) {
          arr = obj.options ? obj.options.children : []
        } else {
          arr = obj.choices || []
        }
        let keyArr = key
        if (!Array.isArray(key)) {
          keyArr = [key]
        }
        const handleFn = (list, keyItem) => {
          list.map(item => {
            if (item.key === keyItem) {
              if (obj.type === 'cascade') {
                str += `${item.value} /`
              } else {
                str += `${item.value} 、`
              }
            }
            if (item.children) {
              handleFn(item.children, keyItem)
            }
          })
        }
        keyArr.forEach(keyItem => {
          handleFn(arr, keyItem)
        })
        str = str.substring(0, str.length - 1)
      } else if (['datetime-range', 'date-range'].includes(obj.type)) { // 时间范围
        if (key && key.length > 0) {
          str = `${key[0]} 至 ${key[1]}`
        }
      } else {
        str = key
      }
    }
    return str || '--'
  }

  private checkHeadersChange (checkList: any, isInit: any) {
    this.$emit('checkHeadersChange', checkList, isInit)
  }

  private handleSizeChange (size: number) {
    this.$emit('pageSizeChange', size)
  }

  private handleCurrentChange (page: number) {
    this.$emit('pageChange', page)
  }

  private batchClick (action: string, selectList: any) {
    this.$emit('batchClick', action, selectList)
  }

  private getRegionCache () {
    return this.$getCache('/base/action/general/cache/query', ['region'], false).then(res => {
      return res
    })
  }

  private getCustomerFiled () {
    return this.$getCache('/server-crm/action/customer/common/fields', ['customerAllFields'], false, false, false, 'GET', false, 'data').then(res => { // 获取全部字段
      return res
    })
  }

  private getCustomerAllLabels () {
    return this.$getCache('/server-crm/action/customer/common/labels', ['customerAllLabels'], true, false, false, 'GET', false, 'data')
  }
}
</script>
<style lang="stylus" scoped>
.delete
  color $c-danger
  cursor pointer
.cus-tags
  display inline-block
  padding 0 12px
  border-radius 12px
  margin 5px
>>> .el-form-item__label
  line-height 1
>>> .oprate
  margin-top 16px
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span, .disable-span
  color $c-danger
.open
  width 70px
  height 32px
  display flex
  align-items center
  justify-content center
  font-size 12px
  color #303854
  border 1px solid #E7E9ED
  border-radius 4px
  margin-right 10px
  cursor pointer
  i
    margin-right 5px
</style>
